package com.sanri.tools.modules.core.service;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;

import java.io.IOException;
import java.util.Date;
import java.util.Timer;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Slf4j
public abstract class CachedData<T> implements InitializingBean {
    protected T data;
    /**
     * 刷新时间间隔
     * 0 表示每次都刷新
     * < 0 表示永不刷新
     * > 0 表示在间隔时间 ms 后刷新
     */
    protected int refreshInterval;
    protected long lastRefreshTime;
    private String name;

    @Override
    public void afterPropertiesSet() throws Exception {
        doRefresh();
    }

    ExecutorService executorService = Executors.newSingleThreadScheduledExecutor();

    private void doRefresh() throws Exception {
        refreshCache();
        this.lastRefreshTime = new Date().getTime();

        if (refreshInterval > 0) {
            executorService.submit(() -> {
                try {
                    refreshCache();
                } catch (Exception e) {
                    log.error("刷新缓存[{}]时异常", name);
                }
            }, refreshInterval);
        }
    }

    protected abstract void refreshCache() throws  Exception;

    public T getData()  {
        if (this.refreshInterval == 0){
            try {
                doRefresh();

            } catch (Exception e) {
                log.error("刷新缓存[{}]时异常2", name );
            }

        }
        return data;
    }

    public void forceCleanCache() throws Exception {
        // 重新刷新
        refreshCache();
    }
}
